'use strict';
app.factory('loginService',function($http, $location, sessionService){
	return{
		
		getLink:function(){
			return 'http://52.28.65.15:8182/v1/admin/';
		},
		
		login:function(data,scope){
			
			
			var $promise=$http.get('http://52.28.65.15:8182/v1/admin/authenticate/'+ data.username+'/'+data.password); 
				
			$promise.success(function(msg) {
			//$promise.then(function(msg){
				
				
				var uid=msg.data;
				 
				
				if(uid){ //alert(uid.id);
					//scope.msgtxt='Correct information';
					sessionService.set('uid',uid);
					sessionService.set('username',msg.data.username);
					sessionService.set('password',msg.data.password);
					sessionService.set('role',msg.data.role);
					sessionService.set('status',msg.data.status);
					
					if ("geolocation" in navigator) {
						navigator.geolocation.getCurrentPosition(function (position) {
							var c = position.coords;
							//$scope.gotoLocation(c.latitude, c.longitude);
							sessionService.set('latitude',c.latitude);
							sessionService.set('longitude',c.longitude);
						});
						//return true;
					}
					
					
					$location.path('/home');
				}	       
				else  {
					scope.msgtxt='incorrect information';
					$location.path('/login');
				}				   
			});
			$promise.error(function(data, status, headers, config) {
	            	alert('wrong username or password');
	          	   
	            });	
		},
		logout:function(){
			sessionService.destroy('uid');
			$location.path('/login');
		},
		islogged:function(){ //alert(sessionService.get('uid'));
			if(sessionService.get('uid') ==null || sessionService.get('status') ==0)
			   $location.path('/login');
            		    
			
			//var $checkSessionServer=$http.post('data/check_session.php');
			return true;
			/*
			if(sessionService.get('user')) return true;
			else return false;
			*/
		},
		getLat:function(){
			return sessionService.get('latitude');
		},
		
		getLon:function(){
			return sessionService.get('longitude');
		},
		
		
		
		getUser:function(){
			if(sessionService.get('uid') ==null)
			   $location.path('/login');
		  
		   var user = {'username':sessionService.get('username'),'password':sessionService.get('password'),'role':sessionService.get('role')}
		   return user;
		},
		
		verify_admin:function(){
			if(sessionService.get('uid') ==null)
			   $location.path('/login');
		  
		    if(sessionService.get('role') ==2){
				return false;
				}
		   
		   return true;
		},
		
		lock_admin:function(){
			if(sessionService.get('role') ==2){
				$location.path('/home');
				}
		   
		   return true;
		},
	}

});